from odoo import fields, models, api
import logging
_logger = logging.getLogger(__name__)
import time
import datetime
class OdooApi(models.Model):
    _name = "odoo.api"

    name = fields.Char()
    

    @api.model
    def hello(self,name):
        return 'hello,'+name

    @api.model
    def create_uom_reference(self,name,code,bitnumber,oppdimen,scalefactor):
        category = {
            "W":'Weight',
            "L":"Length / Distance",
            "A":"面积",
            "V":"Volume",
            "P":"Unit",
            "T":"Working Time",
            "E":"其他"
        }
        uom_map = {
            "个":"Unit(s)",
            "打":"Dozen(s)",
            "千克":'kg',
            "克":"g",
            "秒":"Day(s)",
            "小时":"Hour(s)",
            "吨":"t",
            "米":"m",
            "千米":"km",
            "厘米":"cm",
            "立方米":"Liter(s)",
            "磅":"lb(s)",
            "盎司":"oz(s)",
            "英寸":"inch(es)",
            "英尺":"foot(ft)",
            "英里":"mile(s)",
            "液态盎司":"fl oz",
            "夸脱":"qt",
            "加仑":"gal(s)"
        }
        bit = {
            '0':1,
            '1':0.1,
            '2':0.01,
            '3':0.001,
            '4':0.0001,
            '5':0.00001
        }
        c = self.env['uom.category'].search([('name','=',category[oppdimen])])
        key = uom_map[name] if name in uom_map else 'noname'
        origin_uom = self.env['uom.uom'].search([('name','=',key)])
        if not origin_uom:
            u = self.env['uom.uom'].search([('nc_code','=',code)])
            if not u:
                uom = {}
                uom['category_id'] = c.id
                uom['factor'] = 1/float(scalefactor)
                uom['uom_type'] = 'reference'
                uom['name'] = name
                uom['rounding'] = float(bit[bitnumber]) if bitnumber != 'null' else 1
                uom['nc_code'] = code
                _logger.info(uom)
                self.env['uom.uom'].create(uom)
        else:
            uom = {}
            uom['nc_code'] = code
            uom['factor'] = 1/float(scalefactor)
            uom['name'] = name
            uom['uom_type'] = 'reference'
            uom['rounding'] = float(bit[bitnumber]) if bitnumber != 'null' else 1
            _logger.info(uom)
            origin_uom.write(uom)
        return "ok"
    @api.model
    def create_uom(self,name,code,bitnumber,oppdimen,scalefactor):
        category = {
            "W":'Weight',
            "L":"Length / Distance",
            "A":"面积",
            "V":"Volume",
            "P":"Unit",
            "T":"Working Time",
            "E":"其他"
        }
        bit = {
            '0':1,
            '1':0.1,
            '2':0.01,
            '3':0.001,
            '4':0.0001,
            '5':0.00001
        }
        uom_map = {
            "个":"Unit(s)",
            "打":"Dozen(s)",
            "千克":'kg',
            "克":"g",
            "秒":"Day(s)",
            "小时":"Hour(s)",
            "吨":"t",
            "米":"m",
            "千米":"km",
            "厘米":"cm",
            "升":"Liter(s)",
            "磅":"lb(s)",
            "盎司":"oz(s)",
            "英寸":"inch(es)",
            "英尺":"foot(ft)",
            "英里":"mile(s)",
            "液态盎司":"fl oz",
            "夸脱":"qt",
            "加仑":"gal(s)"
        }
        c = self.env['uom.category'].search([('name','=',category[oppdimen])])
        key = uom_map[name] if name in uom_map else 'noname'
        origin_uom = self.env['uom.uom'].search([('name','=',key)])
        if not origin_uom:
            u = self.env['uom.uom'].search([('nc_code','=',code)])
            _logger.info('----------------------------------')
            _logger.info(name)
            _logger.info(code)
            _logger.info(oppdimen)
            _logger.info(bitnumber)
            _logger.info(scalefactor)
            if not u :
                uom = {}
                if c:
                    uom['category_id'] = c.id
                else:
                    cat = self.env['uom.category'].search([('name','=','其他')])
                    uom['category_id'] = cat.id

                if scalefactor != 'null':
                    uom['factor'] = 1/float(scalefactor)
                    if float(scalefactor) > 1:
                        uom['uom_type'] = 'bigger'
                    if float(scalefactor) < 1:
                        uom['uom_type'] = 'smaller'
                else:
                    uom['factor'] = 1.0
                    uom['uom_type'] = 'bigger'
                uom['factor_inv'] = 1.0
                uom['name'] = name
                uom['rounding'] = float(bit[bitnumber]) if bitnumber != 'null' else 1
                uom['nc_code'] = code
                _logger.info(uom)
                self.env['uom.uom'].create(uom)
        else:
            uom = {}
            if c:
                uom['category_id'] = c.id
            else:
                cat = self.env['uom.category'].search([('name','=','其他')])
                uom['category_id'] = cat.id

            if scalefactor != 'null':
                uom['factor'] = 1/float(scalefactor)
                if float(scalefactor) > 1:
                    uom['uom_type'] = 'bigger'
                if float(scalefactor) < 1:
                    uom['uom_type'] = 'smaller'
            else:
                uom['factor'] = 1.0
                uom['uom_type'] = 'bigger'
            uom['factor_inv'] = 1.0
            uom['rounding'] = float(bit[bitnumber]) if bitnumber != 'null' else 1
            uom['nc_code'] = code
            _logger.info(uom)
            origin_uom.write(uom) 
        return 'ok'

    #创建入库单
    @api.model
    def create_stock_picking(self,vfirstcode,code,neligiastnum,nastnum,company_code,castunitid):
        picking_arrive = self.env['stock.picking'].search([('state','=','done'),('name','=',vfirstcode)])
        product = self.env['product.product'].search([('default_code','=',code)])
        uom = self.env['uom.uom'].search([('nc_code','=',castunitid)])
        _logger.info(vfirstcode)
        _logger.info(product.name)
        _logger.info(product.default_code)
        _logger.info(product.uom_id.id)
        _logger.info(product.uom_id.name)
        _logger.info(product.uom_id.nc_code)
        _logger.info(uom.id)
        _logger.info(uom.name)
        _logger.info(uom.nc_code)
        _logger.info(picking_arrive['origin'])
        res = []
        if picking_arrive['origin']:
            picking = {}
            picking['name'] = vfirstcode+"-INS"
            picking['company_id'] = 1
            picking['location_dest_id'] = 18
            picking['location_id'] = 13
            picking['state'] = 'confirmed'
            picking['move_type'] = "direct"
            picking['origin'] = picking_arrive['origin']
            picking['picking_type_id'] = 5
            p = self.env['stock.picking'].search([('name','=',vfirstcode+"-INS")])
            if not p:
                _logger.info(picking)
                picking_obj = self.env['stock.picking'].create(picking)
                if picking_obj and uom:
                    move = {}
                    move['company_id'] = 1
                    move['picking_id'] = picking_obj.id
                    move['date'] = "2019-10-23 10:10:10"
                    move['date_expected'] = "2019-10-23 10:10:10"
                    move['location_dest_id'] = 12
                    move['location_id'] = 13
                    move['name'] = "test"
                    move['procure_method'] = 'make_to_stock'
                    move['product_id'] = product.id
                    move['product_uom'] = product.product_tmpl_id.uom_id.id
                    move['product_uom_qty'] = neligiastnum
                    _logger.info(product.id)
                    _logger.info("------------------------------")
                    _logger.info(move)
                    m = self.env['stock.move'].create(move)
                    if m:
                        _logger.info("------------------------------")
                        stock_move_line = None
                        for w_stock_move in picking_arrive.move_ids_without_package:
                            if w_stock_move.product_id == m.product_id:
                                for line in w_stock_move.move_line_ids:
                                    if line.product_id == m.product_id:
                                        stock_move_line = line
                        move_line = {}
                        move_line['date'] = "2019-10-23 10:10:10" 
                        move_line['location_dest_id'] = 12
                        move_line['location_id'] = 13
                        move_line['product_id'] = m.product_id.id
                        move_line['product_uom_id'] = m.product_uom.id
                        move_line['product_uom_qty'] = neligiastnum 
                        move_line['picking_id'] = picking_obj.id 
                        move_line['move_id'] = m.id
                        if stock_move_line and stock_move_line.lot_id:
                            move_line['lot_id'] = stock_move_line.lot_id.id
                        1
                        _logger.info(move_line)
                        self.env['stock.move.line'].create(move_line)
                    res.append(picking_obj.id)
                    picking_obj.write({'state': 'confirmed'})
        return res

    #获取采购到货单
    @api.model
    def get_purchase_arrive_order(self,start_time, end_time):
        picking_order_list = self.env['stock.picking'].search([('state','=','done'),('location_dest_id','=',13),('write_date','>=',start_time),('write_date','<=',end_time)])
        order_list = []
        for picking_order in picking_order_list:
            order = {}
            _logger.debug(picking_order.name)
            order_line = []
            order['name'] = picking_order.name
            order['pk_supplier'] = picking_order.partner_id.nc_code
            order['billmaker'] = '00936'
            order['dbilldate'] = picking_order.date_done
            order['approver'] = '03405'
            order['vdef1'] = picking_order.origin

            for line in picking_order.move_lines:
                line_obj = {}
                line_obj['name'] = line.name
                line_obj['pk_receivestore'] = 'DTW'
                line_obj['pk_material'] = line.product_id.product_tmpl_id.default_code
                line_obj['nplanastnum'] = line.product_uom_qty
                line_obj['nastnum'] = line.quantity_done
                line_obj['castunitid'] = line.product_uom.nc_code
                line_obj['vbdef1'] = line.move_line_ids[0].lot_id.id
                order_line.append(line_obj)
            order['orderline'] = order_line
            order_list.append(order)
        return order_list 

    #创建采购订单
    @api.model
    def create_purchase_order(self, nc_code, vbillcode,code_supplier,pk_org,dbilldate, order_line_list):
        partner = self.env['res.partner'].search([('nc_code','=',code_supplier)]) 
        #org = env['res.company'].search(['nc_code','=',pk_org]) 
        _logger.info('-1--')
        order = {}
        r = self.env['purchase.order'].search([('nc_code','=',nc_code)])
        oid = ''
        if not r:
            order['name'] = vbillcode 
            order['date_order'] = dbilldate
            order['partner_id'] = partner.id
            order['company_id'] = 1
            order['state'] = 'purchase'
            order['nc_sync'] = True
            order['nc_code'] = nc_code
            order['currency_id'] = 7
            order['picking_type_id'] = 1
            i = self.env['purchase.order'].create(order)
            if i :
                oid = i.nc_code
        else:
            order['name'] = vbillcode
            order['partner_id'] = partner.id
            order['nc_code'] = nc_code
            r.write(order)
        if i:
            line_ids = []
            for col in order_line_list:
                pro = {}
                _logger.info(col)
                product = self.env['product.product'].search([('default_code','=',col['product_code'])])
                #_logger.info(product)
                if product:
                    pro['product_id'] = product.id
                    pro['name'] = product.product_tmpl_id.name
                    #pro['name'] = '['+product.product_tmpl_id.nc_model+']['+product.product_tmpl_id.nc_specification+']['+product.default_code+']'+product.product_tmpl_id.name
                    pro['price_unit'] = float(col['price'])
                    pro['product_qty'] = float(col['qty'])
                    #pro['date_planned'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    pro['date_planned'] = col['dplanarrvdate']
                    pro['product_uom'] = product.product_tmpl_id.uom_id.id
                    pro['order_id'] = i.id
                    pro['nc_code'] = col['pk_order_b']
                    pro['nc_sync'] = True
                    _logger.info(pro)
                    li = self.env['purchase.order.line'].search([('nc_code','=',col['pk_order_b'])])
                    if not li:
                        line_id = self.env['purchase.order.line'].create(pro)
                    else:
                        li.write(pro)
                    line_ids.append(line_id)
        #_logger.info('----')
        #_logger.info(line_ids)
        return oid
    
